<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <#include "/pubHeadStyleTree.html">
    <script type="text/javascript" src="${ctx}/workflowStatic/js/ZtreeCreator.js"></script>
</head>
<body>
<div style="display: inline-block; padding-left: 25px; width: 850px;height: 90%;overflow: auto;">
    <form class="layui-form" lay-filter="bpmNewFlowTriggerForm" id="bpmNewFlowTriggerForm">
        <div>
            <table class="layui-table">
                <tr>
                    <th width="85px">名称：</th>
                    <td width="120px"><input type="text" name="name" class="layui-input" value="${bpmNewFlowTrigger.name}"></td>
                    <th width="120px">节点：</th>
                    <td><input type="text" name="nodeId" class="layui-input" value="${(bpmNewFlowTrigger??) ? string(bpmNewFlowTrigger.nodeId, nodeId)}"></td>
                </tr>
                <tr>
                    <th>触发动作：</th>
                    <td>
                        <select  name="action" class="layui-input" id="action" lay-filter="action">
                            <option value="">请选择</option>
                            <option value="agree" <#if bpmNewFlowTrigger.action == 'agree'>selected="selected"</#if>>同意</option>
                            <option value="opposite" <#if bpmNewFlowTrigger.action == 'opposite'>selected="selected"</#if>>反对</option>
                            <option value="reject" <#if bpmNewFlowTrigger.action == 'reject'>selected="selected"</#if>>驳回</option>
                            <option value="delete" <#if bpmNewFlowTrigger.action == 'delete'>selected="selected"</#if>>删除</option>
                        </select>
                    </td>
                    <th>启动新流程选择：</th>
                    <td style="line-height: 0px">
                        <input type="hidden" id="triggerFlowKey" name="triggerFlowKey" class="layui-input" value="${bpmNewFlowTrigger.triggerFlowKey}">
                        <input type="text" style="width: 70%!important;float: left" readonly id="triggerFlowName" lay-varify="required" name="triggerFlowName" class="layui-input" value="${bpmNewFlowTrigger.triggerFlowName}">
                        <div style="margin-top: 16px">
                            <a class="iconfont iconicon_add" id="selectFlow" style="cursor: pointer;">选择流程</a>
                        </div>

                    </td>
                </tr>
                <tr>
                    <th>发起人配置：</th>
                    <td colspan="3" style="line-height: 0px">
                        <div style="width: 84.5%!important;float: left;line-height: 38px;height: auto;min-height: 38px;" rtype="8" type="text" id="startUser" name="startUser" value='${receiverInnerCondJsons}' readonly="readonly" class="layui-input token-input">
                        </div>
                        <!--<input style="width: 84.5%!important;float: left" type="text" id="startUser" name="startUser" readonly="readonly" class="layui-input">-->
                        <div style="margin-top: 16px">
                            <a class="iconfont iconicon_setting" id="selectStartUser" style="cursor: pointer;">设置</a>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>描述：</th>
                    <td colspan="3">
                        <textarea  name="note" id="note"  class="layui-textarea">${bpmNewFlowTrigger.note}</textarea>
                    </td>
                </tr>

            </table>
            <input type="hidden" id="triggerId" name="id" value="${bpmNewFlowTrigger.id}" />
            <input type="hidden" id="triggerJson" name="triggerJson" value="${bpmNewFlowTrigger.triggerJson}" />
            <input type="hidden" id="jsonMaping" name="jsonMaping" value="${bpmNewFlowTrigger.jsonMaping}" />
            <input type="hidden" id="flowKey" name="flowKey" value="${(bpmNewFlowTrigger.flowKey??)?string(bpmNewFlowTrigger.flowKey,flowKey)}" />
        </div>
    </form>
    <div class="layui-btn-container" style="text-align: center;position: absolute;bottom: 15px;left: 0px;right: 0px;">
        <a class="layui-btn  layui-btn-md tool_btn" lay-filter="save" lay-submit lay-event="save" style="margin-bottom: 0;">
            <i class="layui-icon"></i>
            <span>保存</span>
        </a>
        <a class="layui-btn layui-btn-danger layui-btn-md tool_btn" lay-event="close" id="del" style="margin-bottom: 0;>
            <i class="layui-icon"></i>
            <span>删除</span>
        </a>
    </div>
    <div>
        <table class="layui-table">
                <thead>
                    <tr>
                        <th width="50%">当前流程表单</th>
                        <th>新流程表单</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="2">
                            <span id="tips" style="color: red"></span>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <ul id="curFormTree" class="ztree" style="height: 185px; overflow: auto;"></ul>
                        </td>
                        <td>
                            <ul id="triggerFormTree" class="ztree" style="height: 185px; overflow: auto;"></ul>
                        </td>
                    </tr>
                </tbody>
        </table>
    </div>
</div>
<style>
    .messageRecipients i{
        font-style: normal;
    }
    .messageRecipients i.layui-icon-close{
        cursor: pointer;
    }
    .messageRecipients{
        display: inline-block;
        line-height: 12px;
        padding: 5px 10px;
        margin-right: 5px;
        background: rgba(8,157,213,0.3);
        border: 1px solid #0b73df;
    }
</style>
<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','table', 'layer', 'jquery', 'form', 'commons','element', 'setter', 'totalFilter', 'common'], function () {
        var table = layui.table,
            layer = layui.layer,
            $ = layui.jquery,
            element = layui.element,
            setter = layui.setter,
            commons = layui.commons,
            form = layui.form;

        var procDefId = '${procDefId}';
        var nodeId = '${nodeId}';
        var receiverInnerCondJsons = ${startUserConditions};
        var curFormTree, triggerFormTree;

        var triggerJson = '${bpmNewFlowTrigger.triggerJson}';
        var jsonMaping = '${bpmNewFlowTrigger.jsonMaping}';
        //消息接收人回显
        if (receiverInnerCondJsons){
            $.each(receiverInnerCondJsons,function (k,v) {
                var htmls = '<span class="messageRecipients"><i>批次号['+v.groupNo+']-'+v.conditionShow+'</i><i value='+v.id+' class="layui-icon layui-icon-close"></i></span>';
                $("#startUser").append(htmls);
            });
            deledeMessage();
        }
        if (triggerJson == '') {
            triggerJson = $.parseJSON('{}');
        }else{
            triggerJson = $.parseJSON('${bpmNewFlowTrigger.triggerJson}');
        }
        if(jsonMaping == ''){
            jsonMaping = $.parseJSON('{}');
        }else {
            jsonMaping = $.parseJSON('${bpmNewFlowTrigger.jsonMaping}');
        }



        loadCurFormTree(jsonMaping);
        loadTriggerFormTree(triggerJson);

        function loadCurFormTree(json) {
            var url = serverPath.workflowPath + setter.workflowLinkPath + "bpmNewFlowTrigger/getTableTreeByDefKey?defKey=${flowKey}&type=cur";
            var ztreeCreator = new ZtreeCreator("curFormTree", url, json)
                .setDataKey({idKey:"fieldId", pIdKey: "tableId", name: "fieldDesc"})
                .setCallback({beforeDrag: beforeDrag, beforeDrop:beforeDrop})
                .initZtree({}, function (treeObj) {
                    curFormTree = treeObj;
                });
        }

        function loadTriggerFormTree(json) {
            var defKey = $("#triggerFlowKey").val();
            if (!defKey) {
                return;
            }

            var url = serverPath.workflowPath + setter.workflowLinkPath + "bpmNewFlowTrigger/getTableTreeByDefKey?defKey=" + defKey;
            var ztreeCreator = new ZtreeCreator("triggerFormTree", url, json)
                .setDataKey({idKey:"fieldId", pIdKey: "tableId", name: "fieldDesc"})
                .setCallback({beforeDrag: beforeDrag, beforeDrop:beforeDrop ,onDrop: onDrop})
                .initZtree({}, function (treeObj) {
                    triggerFormTree = treeObj;
                });
        }

        function beforeDrag(treeId, treeNodes) {
            for(var i=0, l=treeNodes.length; i<l;i++){
                if (treeNodes[i].fieldType == '' || treeNodes[i].style == 'cur') {
                    return false
                }
            }
            return true;
        }

        function beforeDrop(treeId, treeNodes, targetNode, moveType) {
            // cur = A; trigger = B
            // B表 to A表，且只能挂A字段之上
            // 可以回挂至B表上
            if (moveType != 'inner'
                || (targetNode.style == 'trigger' && targetNode.fieldType != 'table')
                || (targetNode.fieldType == 'table' && targetNode.style == 'cur')) {
                return false;
            }

            // 返回目标节点
            if (targetNode.fieldType == 'table' && targetNode.style == 'trigger') {
                if (targetNode.fieldName != treeNodes[0].oldTableName) {
                    $("#tips").html("你回错家了。parentTable:"+treeNodes[0].oldTableName );
                    return false;
                }
                $("#tips").html("");
                return true;
            }

            // 如果A某表字段已经存在B某子表挂接，则不能再挂接B其他表字段
            var targetTable = targetNode.getParentNode();
            var triggerTable = treeNodes[0].getParentNode();
            if(targetTable.type != triggerTable.type){
                $("#tips").html(targetTable.type ==1?"主表只接受主表字段映射":"子表只接受子表映射");
                return false;
            }
            if(targetTable.triggerTableName && targetTable.triggerTableName != triggerTable.fieldName){
                $("#tips").html("目标节点只接受 "+targetTable.triggerTableName+"字段");
                return false;
            }
            targetTable.triggerTableName = triggerTable.fieldName;
            targetTable.targetTableDesc = triggerTable.fieldDesc;
            treeNodes[0].oldTableName = triggerTable.fieldName;
            treeNodes[0].targetTableName = targetTable.fieldName;
            $("#tips").html("");
            return true;
        }

        function onDrop(event, treeId, treeNodes, targetNode, moveType) {

        }


        $("#selectFlow").on('click',function () {
            parent.layer.open({
                type: 2,
                title: "流程选择",
                shade: 0.3,
                area: ['900px', '500px'],
                btn:["选择","关闭"],
                skin: 'btn-class',
                content:serverPath.workflowPath + setter.workflowLinkPath +'actDefModel/view/selector',
                yes:function (index,layero) {
                    //获取iframe的body元素
                    var body = parent.layer.getChildFrame('body',index);
                    //得到iframe页的窗口对象
                    var iframeWin = parent.window[layero.find('iframe')[0]['name']];
                    //执行iframe页的showMsg方法
                    $("#triggerFlowName").val(body.find("input[name=selectedFlowName]").val());
                    $("#triggerFlowKey").val(body.find("input[name=selectedFlowKey]").val());
                    parent.layer.close(index);
                    loadTriggerFormTree();
                    loadCurFormTree();
                }
            });
        });

        $("#selectStartUser").on('click',function () {
            var type = 8;
            parent.layer.open({
                type: 2,
                title: "选择起始人员",
                shade: 0.3,
                area: ['1000px', '585px'],
                content: serverPath.workflowPath + setter.workflowLinkPath +'bpmNodeMessage/receiverSetting?procDefId='+ procDefId + '&nodeId=newFlow_' + nodeId + "&type=" + type,
                end: function () {
                    reloadToken(type);
                }
            });
        });
        function reloadToken(type){
            var url = "${ctx}/workflow/bpmNodeMessage/getReceiverUserCondition";
            var param = {
                procDefId:procDefId,
                nodeId:nodeId,
                receiverType:type
            };

            var tokenContainer = $(".token-input[rtype="+type+"]");

            $.ajax({
                type: "post",
                url: url,
                dataType:"json",
                data:param,
                success:function (result) {
                    if (commons._filterRecord(result)) {
                        $("#startUser").empty();
                        for (var i=0;i<result.data.length;i++){
                            var id = result.data[i].id;
                            var groupNo = result.data[i].groupNo;
                            var name = result.data[i].conditionShow;
                            var htmls = '<span class="messageRecipients"><i>批次号['+groupNo+']-'+name+'</i><i value='+id+' class="layui-icon layui-icon-close"></i></span>'
                            $("#startUser").append(htmls)
                        }
                        deledeMessage();
                    }else{
                        layer.alert(data.msg);
                    }
                }
            });
        }
        function deledeMessage() {
            $('.messageRecipients i.layui-icon-close').click(function () {
                var conditionId = $(this).attr('value'),
                    thet = $(this)
                layer.confirm('确定删除吗？',{title:'提示'}, function(index) {
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        url: "${ctx}/workflow/bpmUserCondition/del",
                        data:{conditionIds:conditionId},
                        success: function (data) {
                            thet.parent().remove();
                            layer.close(index);
                            layer.msg('删除成功',{icon:1})
                        }
                    });


                });
            })
        }
        $("#del").on('click', function () {
            var id = $("#triggerId").val();
            var url = serverPath.workflowPath + setter.workflowLinkPath + "bpmNewFlowTrigger/del";
            if (id) {
                layer.confirm("确定要删除此配置信息吗？", function (index) {
                    $.ajax({
                        type:"post",
                        dataType:"json",
                        url: url,
                        data: {id: id},
                        success: function (result) {
                            layer.alert(result.msg);
                            window.location.reload();
                        }
                    });

                });
            }
        });

        form.on('submit(save)', function (data) {
            if (curFormTree && triggerFormTree) {
                $("#jsonMaping").val(JSON.stringify(curFormTree.getNodes()));
                $("#triggerJson").val(JSON.stringify(triggerFormTree.getNodes()));
            }

            $.ajax({
                method:"post",
                url: serverPath.workflowPath + setter.workflowLinkPath + "bpmNewFlowTrigger/save",
                dataType: "json",
                data: $("#bpmNewFlowTriggerForm").serialize(),
                success: function (result) {
                    if (commons._filterRecord(result)) {
                        window.parent.layer.alert(result.msg, function (thisIndex) {
                            parent.layer.close(thisIndex);
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                        });
                    } else {
                        window.parent.layer.alert(result.msg);
                    }
                }
            });
        });

    });
</script>
</body>
</html>